package org.kaiwo.servlet;

import com.alibaba.fastjson.JSON;
import org.kaiwo.util.SignUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.TreeMap;

/**
 * Created by Medivh on 2018/11/9.
 * 愿我出走半生,归来仍是少年
 */
public class PayTrans {

    public static void main(String asr[]) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        TreeMap<String, String> map = new TreeMap<String, String>();
        map.put("mchtId", "M81017000845");
        map.put("transTime", "20181109135423");
        map.put("orderId", "20181206185541");
        map.put("origOrderId", "20181206185541");
        map.put("orgId", "1144");
        map.put("sign", SignUtil.sign(map));
        String result = sendJson("http://47.105.152.87:8080/gatewaysite/p/transquery", JSON.toJSONString(map));
        System.out.print(result);


    }
    public static String sendJson(String notifyUrl, String json) {

        try {
            byte[] postData = json.getBytes("UTF-8");
            URL url = new URL(notifyUrl);
            // 建立连接，设置连接的属性
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type","application/json");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Length",
                    String.valueOf(postData.length));
            DataOutputStream outStream = new DataOutputStream(
                    conn.getOutputStream());
            outStream.write(postData);
            outStream.flush();
            outStream.close();
            // 将返回的输入流转换成字符串
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            StringBuffer buffer = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "nodata";
    }
}
